<?php
namespace WechatSDK\Lib;


/**
 * 工具
 * @author guibinyu
 * @date 2017-06-15 04:14:50
 */
class Tools
{

	function __construct()
	{
	}

	function __destruct()
	{
        
	}
        /**
     *@todo : 写错误日志
     */
   static public function log($name,$data=array(),$filename='error.log')
    {
        $path = WECHATSDK_LOG_PATH.date('Y_m').$filename;
        error_log(date('Y-m-d H:i:s')."--{$name}=>> ".var_export($data, true)."\r\n", 3, $path);//生成记录文件
       
    }
        /**
         * @todo : 生成随机数
         */
       static public function getRandStr($l = 32, $t = 'str')
        {
            switch ($t)
            {
                case 'str':
                    $str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
                    break;
                case 'upstr':
                    $str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
                    break;
                 case 'lwstr':
                    $str = "abcdefghijklmnopqrstuvwxyz0123456789";
                    break;
                default :
                    $str = "1234567890";
                    break;
            }
             $str = "abcdefghijklmnopqrstuvwxyz0123456789";
            $randStr = str_shuffle($str);
            $rand = substr($randStr, 0, $l);
            return $rand;
        }
         /**
     * 获取签名
     * @param array $arrdata 签名数组
     * @param string $method 签名方法
     * @return bool|string 签名值
     */
    static public function getSha1Signature($arrdata) {
        ksort($arrdata);
        $params = array();
        foreach ($arrdata as $key => $value) {
            $params[] = "{$key}={$value}";
        }
        return sha1(join('&', $params));
    }
 /**
     * 生成安全JSON数据
     * @param array $array
     * @return string
     */
    static public function json_encode($array) {
        return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', create_function('$matches', 'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");'), json_encode($array));
    }
     /**
     * XML编码
     * @param mixed $data 数据
     * @param string $root 根节点名
     * @param string $item 数字索引的子节点名
     * @param string $id 数字索引子节点key转换的属性名
     * @return string
     */
    static public function arrToXml($data, $root = 'xml', $item = 'item', $id = 'id') {
        return "<{$root}>" . self::_data_to_xml($data, $item, $id) . "</{$root}>";
    }

    static private function _data_to_xml($data, $item = 'item', $id = 'id', $content = '') {
        foreach ($data as $key => $val) {
            is_numeric($key) && $key = "{$item} {$id}=\"{$key}\"";
            $content .= "<{$key}>";
            if (is_array($val) || is_object($val)) {
                $content .= self::_data_to_xml($val);
            } elseif (is_numeric($val)) {
                $content .= $val;
            } else {
                $content .= '<![CDATA[' . preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/", '', $val) . ']]>';
            }
            list($_key,) = explode(' ', $key . ' ');
            $content .= "</$_key>";
        }
        return $content;
    }
    /**
     * 将xml转为array
     * @param string $xml
     * @return array
     */
    static public function xmlToArray($xml) {
        return json_decode(Tools::json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    }

	 /**
     * 以get方式提交请求
     * @param $url
     * @return bool|mixed
     */
    static public function httpGet($url) {
       $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }

	 /**
     * 以post方式提交请求
     * @param string $url
     * @param array|string $data
     * @return bool|mixed
     */
    static public function httpPost($url, $data) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        if (version_compare(phpversion(), '5.6') >= 0 && version_compare(phpversion(),'7.0') <0 ) {
			curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
		}
        if (is_array($data)) {
            foreach ($data as &$value) {
                if (version_compare(phpversion(),'7.0') >=0 &&  substr($value, 0,1) == '@') {
                    $value = new \CURLFile(ltrim($value, '@'));
                }
                if (class_exists('\CURLFile')) {
                    $value =  new \CURLFile(realpath(ltrim($value, '@')));
                }
            }
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $data = curl_exec($ch);
//        $status = curl_getinfo($ch);
//        dump($status);
//        $error = curl_error ( $ch );
        curl_close($ch);
        if ($data) {
            return $data;
        }
        return false;
    }
    /**
     * 使用证书，以post方式提交xml到对应的接口url
     * @param string $url POST提交的内容
     * @param array $postdata 请求的地址
     * @param string $ssl_cer 证书Cer路径 | 证书内容
     * @param string $ssl_key 证书Key路径 | 证书内容
     * @param int $second 设置请求超时时间
     * @return bool|mixed
     */
    static public function httpsPost($url, $postdata, $ssl_cer = null, $ssl_key = null, $second = 30) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        /* 要求结果为字符串且输出到屏幕上 */
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        /* 设置证书 */
        if (!is_null($ssl_cer) && file_exists($ssl_cer) && is_file($ssl_cer)) {
            curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
            curl_setopt($ch, CURLOPT_SSLCERT, $ssl_cer);
        }
        if (!is_null($ssl_key) && file_exists($ssl_key) && is_file($ssl_key)) {
            curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
            curl_setopt($ch, CURLOPT_SSLKEY, $ssl_key);
        }
        curl_setopt($ch, CURLOPT_POST, true);
        if (is_array($postdata)) {
            foreach ($postdata as &$data) {
                if (is_string($data) && stripos($data, '@') === 0 && class_exists('CURLFile', FALSE)) {
                    $data = new CURLFile(realpath(trim($data, '@')));
                }
            }
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        $result = curl_exec($ch);
        curl_close($ch);
        if ($result) {
            return $result;
        } else {
            return false;
        }
    }

}
?>